package org.example.backend.demos.web.UserModule.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.example.backend.demos.web.UserModule.entity.LoginDTO;
import org.example.backend.demos.web.UserModule.entity.LoginResult;
import org.example.backend.demos.web.UserModule.entity.User;
import org.example.backend.demos.web.UserModule.entity.UserDTO;
import org.example.backend.demos.web.UserModule.service.UserService;
import org.example.backend.demos.web.Util.JwtTokenUtil;
import org.example.backend.demos.web.common.CheckResult;
import org.example.backend.demos.web.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class UserController {

    private static final Logger log = LogManager.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 用户注册后就是伪志愿者
     * 未注册的是访客
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody UserDTO userDTO) {
        // 参数校验
        if (userDTO.getUsername() == null || userDTO.getUsername().trim().isEmpty()) {
            return Result.error("用户名不能为空");
        }
        if (userDTO.getPassword() == null || userDTO.getPassword().trim().isEmpty()) {
            return Result.error("密码不能为空");
        }
        if (userDTO.getPhone() == null || userDTO.getPhone().trim().isEmpty()) {
            return Result.error("手机号不能为空");
        }

        User user = userService.register(userDTO);
        return Result.success("注册成功", user);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResult> login(@RequestParam String username,@RequestParam String password) {

        LoginDTO dto = new LoginDTO();
        dto.setUsername(username);
        dto.setPassword(password);
        // 参数校验
        if (dto.getUsername() == null || dto.getUsername().trim().isEmpty()) {
            return Result.error("用户名不能为空");
        }
        if (dto.getPassword() == null || dto.getPassword().trim().isEmpty()) {
            return Result.error("密码不能为空");
        }
//        if (dto.getLoginType() == null ||
//                (!"user".equals(dto.getLoginType()) && !"admin".equals(dto.getLoginType()))) {
//            return Result.error("登录类型必须为user或admin");
//        }

        LoginResult loginResult = userService.login(dto);
        return Result.success("登录成功", loginResult);
    }
    /**
     * 用户退出登录
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request, HttpServletResponse response) {
        // Spring Security的注销流程
        SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();
        logoutHandler.logout(request, response, SecurityContextHolder.getContext().getAuthentication());
        return Result.success("退出登录成功");
    }


    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check-username")
    public Result<CheckResult> checkUsername(@RequestParam String username) {
        SecurityContext context = SecurityContextHolder.getContext();
        context.getAuthentication().getPrincipal();
        if (username == null || username.trim().isEmpty()) {
            return Result.error("用户名不能为空");
        }

        boolean exists = userService.usernameExists(username);
        CheckResult result = new CheckResult(exists, exists ? "用户名已存在" : "用户名可用");
        return Result.success(result);
    }

    /**
     * 检查手机号是否存在
     */
    @GetMapping("/check-phone")
    public Result<CheckResult> checkPhone(@RequestParam String phone) {
        if (phone == null || phone.trim().isEmpty()) {
            return Result.error("手机号不能为空");
        }

        boolean exists = userService.phoneExists(phone);
        CheckResult result = new CheckResult(exists, exists ? "手机号已存在" : "手机号可用");
        return Result.success(result);
    }
}